<template>
  <!-- 在主容器上添加v-loading属性 -->
  <div class="filter-panel" v-loading="loading">
    <!-- 筛选内容 - 当loading为false时自动显示 -->
    <!-- 展开区域 -->
    <el-collapse-transition>
      <div class="filter-body">
        <div
          v-for="(group, key, index) in filterMap"
          :key="key"
          class="filter-group"
          :class="{ 'filter-group--hidden': isFold && index >= defaultShowCount }"
        >
          <div class="filter-label">{{ group.label }}：</div>
          <div class="filter-tags-container">
            <!-- 所有选项水平排列，但"全部"选项有特殊样式 -->
            <el-check-tag
              v-for="opt in group.options"
              :key="opt.value"
              :checked="isChecked(key, opt.value)"
              @change="toggleTag(key, opt.value)"
              :class="{
                'filter-tag--selected': isChecked(key, opt.value),
                'filter-tag--all': opt.label === '全部'
              }"
            >
              {{ opt.label }}
            </el-check-tag>
          </div>
        </div>
      </div>
    </el-collapse-transition>

    <!-- 底部操作栏 -->
    <div class="filter-toolbar">
      <div class="fold-section">
        <el-button link type="primary" @click="toggleFold" class="fold-button">
          {{ isFold ? '展开筛选条件' : '收起筛选条件' }}
        </el-button>
        <img
          src="@/assets/imgs/data/expand.png"
          class="fold-icon"
          :class="{ 'fold-icon--rotated': isFold }"
          @click="toggleFold"
        />
      </div>
      <!-- <el-button link type="primary" @click="resetAll">重置</el-button> -->
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, defineEmits } from 'vue'
import * as PortalApi from '@/api/portal'
import { useSearchStore } from '@/store/modules/search'

const searchStore = useSearchStore()
const emit = defineEmits<{
  (e: 'change', payload: Record<string, string>): void
}>()

/* -------------------- 折叠 -------------------- */
const isFold = ref(true)
const defaultShowCount = 3 // 默认显示3个筛选条件
const toggleFold = () => (isFold.value = !isFold.value)

/* -------------------- 数据结构 -------------------- */
interface Option {
  label: string
  value: string
}

interface Group {
  label: string
  options: Option[]
}

const filterMap = reactive<Record<string, Group>>({})
const loading = ref(true) // 加载状态
/* -------------------- 选中状态 -------------------- */
const selected = reactive<Record<string, string>>({}) // 改为每个类型只存储一个选中的值

/* -------------------- 初始化数据 -------------------- */
const initFilterData = async () => {
  loading.value = true // 开始加载
  try {
    // 定义需要获取的字典类型（按指定顺序）
    const dictTypes = [
      'topicClass',
      'industryClass',
      'shareProperty',
      'subjectFeature',
      'businessDomain',
      'businessClass',
      'subjectType',
      'manageObjClass'
    ]

    // 顺序获取字典数据，确保展示顺序
    for (const dictType of dictTypes) {
      try {
        const response = await PortalApi.getDictByCode({ dictType })

        if (response && response.length > 0) {
          // 转换数据格式，添加"全部"选项
          const options = [
            { label: '全部', value: '' },
            ...response.map((item) => ({
              label: item.label,
              value: item.value || item.label
            }))
          ]

          // 设置对应的filterMap数据
          filterMap[dictType] = {
            label: getDictLabel(dictType),
            options
          }

          // 初始化选中状态为"全部"
          selected[dictType] = ''
        }
      } catch (error) {
        console.error(`获取字典类型 ${dictType} 失败:`, error)
        // 设置默认空数据
        filterMap[dictType] = {
          label: getDictLabel(dictType),
          options: [{ label: '全部', value: '' }]
        }
        selected[dictType] = ''
      }
    }
  } catch (error) {
    console.error('初始化筛选数据失败:', error)
  } finally {
    loading.value = false // 加载结束，无论成功或失败

    if (searchStore.filterParams) {
      nextTick(() => {
        handleExternalFilter(searchStore.filterParams)
      })
    }
  }
}

// 获取字典类型对应的中文标签
const getDictLabel = (dictType: string): string => {
  const labelMap: Record<string, string> = {
    businessDomain: '主营业务领域',
    subjectType: '主题类型',
    subjectFeature: '主题特征',
    industryClass: '行业分类',
    businessClass: '业务分类',
    manageObjClass: '管理对象分类',
    topicClass: '主题分类',
    shareProperty: '共享属性'
  }
  return labelMap[dictType] || dictType
}

/* -------------------- 选中状态 -------------------- */
const isChecked = (groupKey: string, val: string) => selected[groupKey] === val

const toggleTag = (groupKey: string, val: string) => {
  // 同一类型内单选：直接设置新值
  selected[groupKey] = val
  emitFilter()
}

const emitFilter = () => {
  // 过滤掉值为空的筛选条件
  const payload: Record<string, string> = {}
  Object.keys(selected).forEach((key) => {
    if (selected[key]) {
      payload[key] = selected[key]
    }
  })
  emit('change', payload)
}

// 组件挂载时初始化数据
onMounted(() => {
  initFilterData()
})

// 处理外部传入的筛选参数
const handleExternalFilter = (params: {
  filterType: string
  filterValue: string
  filterLabel: string
}) => {
  const { filterType, filterValue, filterLabel } = params

  // debugger
  // 查找对应的筛选组 - 直接使用filterMap而不是filterMap.value
  const filterGroup = filterMap[filterType]

  if (!filterGroup) return

  // 确保筛选组是展开状态 - 移除isFold检查，因为filterGroup没有isFold属性
  // 这里需要确保筛选面板是展开的
  if (isFold.value) {
    isFold.value = false
  }

  // 设置选中状态 - 直接使用selected而不是selected.value
  selected[filterType] = filterValue

  // 触发筛选事件
  const payload = {
    [filterType]: filterValue
  }

  emit('change', payload)

  // 清除searchStore中的筛选参数，避免重复触发
  searchStore.clearFilterParams()
}
</script>

<style scoped lang="scss">
$primary-color: #009eff;
$text-color: #666666;
$border-radius: 20px;
$spacing: 16px;
$default-bg: #f8f9fa;
$hover-bg: #e6f3ff;

.filter-panel {
  padding: 16px;
  min-height: 200px; /* 确保有足够空间显示加载动画 */
}

.filter-body {
  margin-bottom: $spacing;

  .filter-group {
    display: flex;
    align-items: flex-start;
    margin-bottom: 20px;
    transition: all 0.3s ease-in-out; // 添加过渡动画
    max-height: 1000px; // 设置足够大的最大高度
    opacity: 1; // 默认不透明
    overflow: hidden; // 隐藏溢出的内容

    &:last-child {
      margin-bottom: 0;
    }

    // 添加隐藏类 - 使用动画效果
    &.filter-group--hidden {
      max-height: 0 !important; // 高度收缩为0
      margin-bottom: 0 !important; // 移除底部间距
      opacity: 0 !important; // 完全透明
      transform: translateY(-10px); // 轻微上移效果
      pointer-events: none; // 禁止交互
    }

    .filter-label {
      min-width: 200px;
      text-align: right;
      padding-right: $spacing;
      color: $text-color;
      font-size: 14px;
      font-weight: normal;
      flex-shrink: 0;
      line-height: 36px;
      transition: opacity 0.3s ease-in-out;
    }

    .filter-tags-container {
      flex: 1;
      display: flex;
      flex-wrap: wrap;
      gap: 12px;
      align-items: flex-start;
      transition: opacity 0.3s ease-in-out;

      // 为"全部"选项设置特殊样式，使其占据独立位置
      :deep(.el-check-tag.filter-tag--all) {
        min-width: 80px;
        text-align: center;
        background: $default-bg;
        border: 1px solid #e4e7ed;
        order: -1; // 确保"全部"始终在最前面
        margin-right: 12px;

        &.filter-tag--selected {
          background: $primary-color;
          border-color: $primary-color;
          color: #fff;
        }

        &:hover {
          background: $hover-bg;
          border-color: $primary-color;
        }
      }

      // 通用标签样式
      :deep(.el-check-tag) {
        padding: 8px 18px;
        border-radius: 16px;
        font-size: 14px;
        font-weight: normal;
        color: $text-color;
        background: $default-bg;
        transition: all 0.3s ease;

        &:hover {
          background: $hover-bg;
          border-color: $primary-color;
          color: $primary-color;
        }

        &.filter-tag--selected {
          background: $primary-color;
          border-color: $primary-color;
          color: #fff;
          border-radius: $border-radius;

          &:hover {
            background: darken($primary-color, 10%);
            border-color: darken($primary-color, 10%);
          }
        }
      }
    }
  }
}

.filter-toolbar {
  display: flex;
  justify-content: center;
  align-items: center;
  padding-top: $spacing;
  border-top: 1px solid #e8e8e8;

  .fold-section {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    cursor: pointer;
    background: linear-gradient(180deg, #eff4fa 0%, #ffffff 100%);
    border-radius: 10px 10px 0px 0px;
    // border: 1px solid;
    border-image: linear-gradient(180deg, rgba(177, 197, 209, 1), rgba(177, 197, 209, 0)) 1 1;
    padding: 8px 16px;

    .fold-icon {
      width: 16px;
      height: 16px;
      transition: transform 0.3s ease-in-out;

      &.fold-icon--rotated {
        transform: rotate(180deg);
      }

      &:hover {
        opacity: 0.8;
      }
    }
  }

  .fold-button {
    margin: 0 auto;
    transition: all 0.3s ease;

    &:hover {
      transform: scale(1.05); // 悬停时轻微放大
    }
  }

  :deep(.el-button) {
    & + .el-button {
      margin-left: $spacing;
    }
  }
}
</style>
